import React, {useEffect, useRef, useState} from "react";
import {Button, Modal, TextArea} from "@douyinfe/semi-ui";
import {IconQuit, IconRefresh, IconMaximize, IconMinimize, IconArrowRight } from "@douyinfe/semi-icons";
import {store} from "../../redux";
import {IEvent, Terminal} from 'xterm';
import { WebLinksAddon } from 'xterm-addon-web-links';
import { FitAddon } from 'xterm-addon-fit';
import { AttachAddon } from 'xterm-addon-attach';
import 'xterm/css/xterm.css';

interface ServerTerminalProp {
    visible: boolean;
    id: number;
    closeModel: () => void;
}

const stateArr: WsState[] = [
    {key: 0, value: '正在连接中'},
    {key: 1, value: '已经连接并且可以通讯'},
    {key: 2, value: '连接正在关闭'},
    {key: 3, value: '连接已关闭或者没有连接成功'},
];

interface WsState {
    key: number;
    value: string;
}

interface MessageData {
    msgType: number;
    data: string;
}

export const ServerTerminal: React.FC<ServerTerminalProp> = ({visible, id, closeModel}) => {

    const divRef: any = useRef(null);

    const [full, setFull] = useState<boolean>(false);

    const [value, setValue] = useState<string>('');

    const ws = useRef<WebSocket | null>(null);
    const terminal = useRef<Terminal | null>(null);

    //  socket 状态
    const [readyState, setReadyState] = useState<WsState>({ key: 0, value: '正在连接中' })

    const enterValue = () => {
        ws.current?.send(JSON.stringify({msgType: 4, data: value}))
    }

    const close = () => {
        ws.current?.close();
        closeModel();
    }

    useEffect(() => {
        let timer: number | null = null;
        if (readyState.key === 1) {
            timer = setInterval(() => {
                ws.current?.send(JSON.stringify({msgType: 2, data: "ping"}))
            }, 10000);
        }
        if ((readyState.key === 2 || readyState.key === 3) && timer) {
            clearInterval(timer);
        }
        return () => {
            if (timer) {
                clearInterval(timer);
            }
        }
    }, [readyState])

    useEffect(() => {
        if (visible) {
            // 初始化ws
            try {
                const token = store.getState().user.token;
                ws.current = new WebSocket('ws://127.0.0.1:8081/api/ws')
                ws.current.onopen = () => {
                    ws.current?.send(JSON.stringify({msgType: 1, data: token, id: id}))
                    setReadyState(stateArr[ws.current?.readyState ?? 0]);
                }
                ws.current.onclose = () => {
                    setReadyState(stateArr[ws.current?.readyState ?? 0])
                }
                ws.current.onerror = () => {
                    setReadyState(stateArr[ws.current?.readyState ?? 0])
                }
                ws.current.onmessage = (e) => {
                    console.log("e => ", e)
                    // setValue(value + e.data)
                }
            } catch (error) {
                console.log(error)
            }

            terminal.current = new Terminal({
                cursorBlink: true, // 光标闪烁
                allowProposedApi: true,
                disableStdin: false, //是否应禁用输入
                cursorStyle: "underline", //光标样式
                theme: {
                    foreground: "yellow", //字体
                    background: "#060101", //背景色
                    cursor: "help", //设置光标
                },
            });
            const webLinksAddon = new WebLinksAddon();
            const fitAddon = new FitAddon();
            const attachAddon = new AttachAddon(ws.current!);
            terminal.current.loadAddon(webLinksAddon);
            terminal.current.loadAddon(fitAddon);
            terminal.current.loadAddon(attachAddon);
            terminal.current?.onData(e => {
                ws.current?.send(JSON.stringify({msgType: 4, data: e}))
            })
            terminal.current.open(divRef.current);
            fitAddon.fit();

        }
        return () => {
            ws.current?.close();
            terminal.current?.dispose()

        }
    }, [visible])

    return <Modal
        title="服务器控制台"
        maskClosable={false}
        width={1300}
        visible={visible}
        onOk={closeModel}
        onCancel={close}
        closeOnEsc={true}
        fullScreen={full}
        footer={<>

            <Button type="tertiary" icon={full ? <IconMinimize /> : <IconMaximize />} theme={'solid'} onClick={() => setFull(!full)}>{full ? '窗口' : '全屏'}</Button>
            <Button type="primary" icon={<IconArrowRight />} theme={'solid'} onClick={enterValue}>输入</Button>
            <Button type="primary" icon={<IconRefresh />} theme={'solid'}>重载</Button>
            <Button type="danger" icon={<IconQuit />} theme={'solid'} onClick={close}>关闭</Button>
        </>}
    >
        {/*<TextArea rows={6} value={value} onChange={e => setValue(e)} showClear/>*/}
        <div style={{ marginTop: 10, width: 1250, height: 600 }} ref={divRef} />
    </Modal>

}